package tokenBuket

import (
	"context"
	"errors"
	log "github.com/sirupsen/logrus"
	"queue-gateway/databases"
	"time"
)

// AcquireLock 获取分布式锁
func AcquireLock(ctx context.Context, uuid string) error {
	// redis操作

	// 尝试多次加锁
	for i := 0; i < 3; i++ {
		result := databases.Rdb.SetNX(ctx, uuid, 1, 3*time.Second)
		if result.Err() != nil || !result.Val() {
			// 等待之后再次去加锁
			time.Sleep(1 * time.Millisecond)
			continue
		}
		return nil
	}
	return errors.New("set distribute lock failed")
}

// ReleaseLock 释放分布式锁
func ReleaseLock(ctx context.Context, uuid string) {

	if err := databases.Rdb.Del(ctx, uuid).Err(); err != nil {
		log.Error("redisClient.Del failed,err:%v", err)
	}
}
